/**
 * 
 */
package com.roc.util;

import java.io.IOException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * @author RenPengFei 2013-4-20 下午10:05:49
 */
public class Utils {

	static Logger logger = LogManager.getLogger(Utils.class);

	private Utils() {
	}

	public static boolean isBlank(String value) {
		return StringUtils.isBlank(value);
	}
	
	
	public static String dealRespCodeName(String resoCodeName){
		if(isBlank(resoCodeName)){
			return "失败";
		}
		return resoCodeName;
	}
	
	public static String dealRespCodeNames(String resoCode){
		if(isBlank(resoCode)){
			return "交易超时";
		}
		if("00".equals(resoCode)){
			return "交易成功";
		}
		if("51".equals(resoCode)){
			return "余额不足";
		}
		if("55".equals(resoCode)){
			return "密码码错";
		}
		if("96".equals(resoCode)){
			return "系统异常";
		}
		if("A0".equals(resoCode)){
			return "MAC检验失败";
		}
		return "交易失败";
	}
	public static String dealRespCodeName(String resCode,Map<String, String> resCodes){
		if(isBlank(resCode)){
			return "交易超时";
		}
		String resCodeName=resCodes.get(resCode);
		if(isBlank(resCodeName)){
			return resCode;
		}
		return resCodeName;
	}
	public static String dealCardNo(String value) {
		if(value==null||value==""){
			return "";
		}
		if(value.length()<16){
			return value;
		}
		String temp=value.substring(6,value.length()-4);
		return value.replace(temp, dealWithSpecial(temp));
				
				
	}
	
	public static String dealCardNoTwo(String value) {
		if(value==null||"".equals(value)){
			return "";
		}
		
		String temp=value.substring(6,value.length()-4);
		return value.replace(temp, dealWithSpecial(temp));
				
				
	}
	public static String editTransType(String[] value) {
		String  tranTypes="0";
		
		String  a="";
		for (int i = 0; i <128; i++) {
			String  is="0";
			for (String str : value) {
				if(i==Integer.parseInt(str)){
					//System.err.println("str==="+str);
					is="1";
					break;
				}
			}
			
		 	tranTypes=a+is;
			a=tranTypes;
		}
		return tranTypes;
	}
	public static String[] editTransType(String value) {
		String[] str=new String[128];
		int b=0;
		int lengths=0;
		
		for (int i = 1; i <= value.length(); i++) {
			String a=value.substring(b,i);
			if(a.equals("1")){
				str[i-1]=Integer.toString(i-1);
				lengths++;
			}
			b++;
		}
		String[] returns=new String[lengths];
		int c=0;
		for (int j=0;j<str.length;j++) {
			if(str[j]!=null){
				
				returns[c]=str[j];
				c++;
			}
		}
		return returns;
	}
	public static String dealMobile(String value) {
		if(value==null||value==""){
			return "";
		}
		if(value.length()<11){
			return value;
		}
		String temp=value.substring(3,value.length()-4);
		return value.replace(temp, dealWithSpecial(temp));
		
	}
	
	public static String dealRealName(String value){
		if(value == null || value == ""){
			return "";
		}
		String indexOneStr = value.substring(0, 1);
		String indexLast = value.substring(1);
		return indexOneStr+dealWithSpecial(indexLast);
	}
	
	public static String dealWithSpecial(String obj){
		if(obj==null||obj.length()==0){
			return "";
		}
		String temp="";
		for(int i=0;i<obj.length();i++){
			temp+="*";
		}
		return temp;
	}
	public static Properties getProperties(){
		Properties prop = new Properties();   
		InputStream is= Utils.class.getResourceAsStream("/config.properties");
		try {
			prop.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return prop;
	}
	
	public static String getConfigValue(String objKey){
		Properties pro=Utils.getProperties();
		return  pro.getProperty(objKey);
	}
	
	public static boolean isNeededFapiao(String orgCode){
		String orgs=getProperties().getProperty("org_fapiao");
		String[] org_array=null;
		if(orgs!=null&&orgs.length()>0){
			org_array=orgs.split("\\|");
		}
		if(org_array!=null&&org_array.length>0){
			for(String obj:org_array){
				if(obj.equals(orgCode)){
					return true;
				}
			}
		}
		
		return false;
	}
	
	public static String getRandom() {
	   String code="";
	   int random = Math.abs(new java.util.Random().nextInt()) % 900000 + 100000;
	   code=String.valueOf(random);
	   return code;
    }
	
	
	public static String getRandomAmount() {
		   String amount="";
		   int random = Math.abs(new java.util.Random().nextInt()) % 900000 + 100000;
		   amount=String.valueOf(random/100.00);
		   return amount;
	    }
	
	public static String dealDefaultPwd(String mobile){
		if(mobile==null||mobile.length()==0){
			return "";
		}
		int len=mobile.length();
		if(len<=6){
			return mobile;
		}
		
		return mobile.substring(len-6,len);
	}
	
	//随机获取10位密码
	public static String getpass(int length) {
		  char[] ss = new char[length];
		  int i=0;
		 while(i<length) {
		     int f = (int) (Math.random()*3);
		     if(f==1)  
		      ss[i] = (char) ('a'+Math.random()*26);
		     else 
		      ss[i] = (char) ('0'+Math.random()*10);    
		     i++;
		  }
		 String is=new String(ss);
		  return is;
	} 
	
	
	public static void main(String[] args) {
		String s= getpass(6);
		
		System.out.print(s);
		//System.out.println(Utils.getConfigValue("user"));
		//System.out.println(Utils.getConfigValue("pass"));
		//System.out.println(Utils.getConfigValue("httpUrl"));
		//String s="13122397736";
		//System.out.println(s.substring(s.length()-6,s.length()));
		//System.out.println(getConfigValue("profit_model_needed"));
		/*for(Long i=952700010025000l;i<=952700010029999l;i++){
			System.out.println(i);
		}*/
		//System.out.println("20140616".substring(0,4));
//		System.out.println(dealCardNo("6222021001037663611"));
//		System.out.println(dealMobile("18616630759"));
//		System.out.println(editTransType(new String[]{"9",
//				"13",
//				"15",
//				"22",
//				"31",
//				"35",
//				"43",
//				"55"}));
//		System.out.println(replace("623020******4666","*" , "_"));
	}
	
	/**
	 * 将字符串中含有小写字母的转换成大写字母
	 * @param str
	 * @return
	 */
	public static String changeCharUpperCase(String str) {
		StringBuffer sb = new StringBuffer();
		if (str != null) {
			for (int i = 0; i < str.length(); i++) {
				char c = str.charAt(i);
				if (Character.isUpperCase(c)) {
					sb.append(c);
				} else if (Character.isLowerCase(c)) {
					sb.append(Character.toUpperCase(c));
				} else {
					sb.append(c);
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * 翻译交易流水表的Trans_ST字段的含义
	 * @return
	 */
	public static String dealTransSt(String str,String st){
		String first = "";
		String second ="";
		String third="";
		//实时收款
		if("1171".equals(str)){
			first = st.substring(0,1);
			if("1".equals(first)){
				return "正常";
			}
			return "异常";
		}
		//消费
		if("1011".equals(str)){
			first = st.substring(0,1);
			if("1".equals(first)){
				second = st.substring(1,2);
				if(!"0".equals(second)){
					return "被冲正";
				}
				third = st.substring(2,3);
				if(!"0".equals(third)){
					return "被撤销";
				}
				return "正常";
			}
			return "异常";
		}
		
		//冲正
		if("4011".equals(str)){
			first = st.substring(0,1);
			if("1".equals(first)){
				return "正常";
			}
			return "异常";
		}
		
		//撤销
		if("2011".equals(str)){
			first = st.substring(0,1);
			if("1".equals(first)){
				return "正常";
			}
			return "异常";
		}
		//银联  微信  支付宝
		if("1161".equals(str)||"1191".equals(str)
		 ||"1261".equals(str)||"1291".equals(str)
		 ||"1361".equals(str)||"1391".equals(str)
		 ||"1461".equals(str)||"1491".equals(str)
		 ||"1561".equals(str)||"1591".equals(str)
		 ||"1661".equals(str)||"1691".equals(str)){
			first = st.substring(0,1);
			if("1".equals(first)){
				return "正常";
			}
			return "异常";
		}
		
		return "异常";
	}
	
	public static String replace(String obj,String fromStr,String toStr){
		if(obj==null||obj.length()==0){
			return "";
		}
		
		return obj.replace(fromStr, toStr);
	}
	/**
	 * 验证由数字和26个英文字母组成的字符串 (sn设备号)
	 * @param positiveInteger 匹配数字和26个英文字母
	 * @return 验证成功返回true，验证失败返回false
	 */
	public static boolean checkSnCode(String number){
		String regex = "^[A-Za-z0-9]+[-]?[A-Za-z0-9]+$";
		return Pattern.matches(regex, number);
	}
	/**
	 * 验证sn设备号长度
	 * @param number sn设备号
	 * @param lengths 当前型号的长度数组,如:8,10
	 * @return 验证成功返回true，验证失败返回false
	 */
	public static boolean checkSnCodeLength(String number,String lengths){
		boolean flag = false;
		if(null != lengths && lengths.length() > 0){
			String [] arr = lengths.split("/");
			for (String leg : arr) {
				if(number.length() == Integer.parseInt(leg)){
					flag = true;
					break;
				}
			}
			
		}else{
			flag = true;
		}
		return flag;
	}

	/**
	 * @return 是否直属代理商集合
	 */
	public static Map<String,String> getIsDirectlyMap(){
		Map<String,String> isDirectlyMap=new LinkedHashMap<String,String>();
		isDirectlyMap.put("1", "否");
		isDirectlyMap.put("0", "是");
		return isDirectlyMap;
	}

	/**
	 * @return SN 资产类型集合
	 */
	public static Map<String,String> getSnAssefMap(){
		Map<String,String> isDirectlyMap=new LinkedHashMap<String,String>();
		isDirectlyMap.put("0", "公司直采");
		isDirectlyMap.put("1", "公司代采");
		isDirectlyMap.put("2", "携机入网");
		return isDirectlyMap;
	}
	/**
	 * @return 入网条件(定制机/携机入网)
	 */
	public static Map<String,String> getNetInTypeMap(){
		Map<String,String> netInTypeMap=new LinkedHashMap<String,String>();
		netInTypeMap.put("0", "定制机");
		netInTypeMap.put("1", "携机入网");
		return netInTypeMap;
	}
	/**
	 * @return 是否已刷288交易
	 */
	public static Map<String,String> getUse288Map(){
		Map<String,String> netInTypeMap=new LinkedHashMap<String,String>();
		netInTypeMap.put("0", "否");
		netInTypeMap.put("1", "是");
		return netInTypeMap;
	}
	/**
	 * @return 云商宝是否直属集合
	 */
	public static Map<String,String> getYsbIsDirectlyMap(){
		Map<String,String> isDirectlyMap=new LinkedHashMap<String,String>();
		isDirectlyMap.put("0", "本级");
		isDirectlyMap.put("1", "直属下级");
		return isDirectlyMap;
	}
	/**
	 * @return 云商宝SN等级
	 */
	public static Map<String,String> getYsbSnClassMap(){
		Map<String,String> ysbSnClassMap=new LinkedHashMap<String,String>();
		ysbSnClassMap.put("A", "88");
		ysbSnClassMap.put("B", "188");
		ysbSnClassMap.put("C", "288");
		ysbSnClassMap.put("D", "0");
		return ysbSnClassMap;
	}
	/**
	 * @return 15天无交易 查询范围 
	 */
	public static Map<String,String> getNoEstrn15RangeMap(){
		Map<String,String> isDirectlyMap=new LinkedHashMap<String,String>();
		isDirectlyMap.put("0", "15天");
		isDirectlyMap.put("1", "一个月");
		return isDirectlyMap;
	}
	/**
	 * 截取时分秒 如 0823065720333 ---> 065720
	 * @param datetime 时间 包含毫秒
	 * @return 时间 (时分秒) 
	 */
	public static String getTime(String datetime){
		String time = "";
		time = datetime.substring(4,10);
		return time;
	}
	/**
	 * 左边补0
	 * @param zeroLength 0的个数，如 00023，0的个数为 3
	 * @param number 数值
	 * @return 补0后的字符串  如 3，23， return 00023
	 */
	public static String addLeftZero(int zeroLength, Long number ){
		StringBuffer str = new StringBuffer();
		for (int s = 0; s < zeroLength ; s++) {
			str.append("0");
		}
		str.append(number);
		return str.toString();
	}

	/**
	 * 验证由数字/26个英文字母（中英文）和中文以及 '()','（）'组成的字符串 (商户/代理商名称) 例如：IBM(北京)有限公司1
	 * @param positiveInteger 匹配数字/26个英文字母（中英文）和中文以及 '()','（）'
	 * @return 验证成功返回true，验证失败返回false
	 */
	public static boolean checkAccountName(String number){
		String regex = "^[\\(\\)\\（\\）\\u4E00-\\u9FA5 A-Za-z0-9]+$";
		return Pattern.matches(regex, number);
	}

	public static String getRandomString(){
		String str = "";
	//	int minLength = 6;
	//	int maxLength = 12;
		
		char[] chrNumber = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		char[] chrEnglith = { 
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
			//	, 
			//	'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' 
				};
/*
		char[] chrSpecialChar = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '{', '}', '\\', '|', 
				';', ':', '\'', '"', ',', '<', '.', '>', '/', '?' };*/
		
		StringBuffer sbf = new StringBuffer();

		getRandomChar(sbf, chrNumber); // 随机生成3位或4位的数字
		getRandomChar(sbf, chrEnglith); // 随机生成3位或4位的英文
//		getRandomChar(sbf, chrSpecialChar); // 随机生成2位或4位的特殊字符
	//	System.out.println("打乱前：" + sbf.toString());
		str = shuffleForSortingString(sbf.toString()); // 随机打乱字符串顺序
	//	System.out.println("打乱后：" + str);
		return str;
	}
	 public static void getRandomChar(StringBuffer sbf,char[] chrArr ) {

			// int randNum = rand.nextInt(22)+5;// 随机生成 5－26之间的随机数，包括26
			Random rand = new Random();
			int circulateCount = rand.nextInt(2) + 3; // for循环次数
			
			for (int i = 0; i < circulateCount ; i++) {
				int charSize = rand.nextInt(chrArr.length) ; // 生成最大为数组长度的数字
				sbf.append(chrArr[charSize]);
			}
	 }
	 
	 public static String shuffleForSortingString(String s) {
	        char[] c = s.toCharArray();
	        List<Character> lst = new ArrayList<Character>();
	        for (int i = 0; i < c.length; i++) {
	            lst.add(c[i]);
	        }
	 
	        Collections.shuffle(lst);
	 
	        String resultStr = "";
	        for (int i = 0; i < lst.size(); i++) {
	            resultStr += lst.get(i);
	        }
	        return resultStr;
	    }
}
